﻿'use strict';
/**--
指令使用方法说明：
newstart-textarea 指令名，参数为ng-model的变量，系统自动与之双向绑定，
newstart-btn="face,fujian" （可选）用于控制显示的功能，没有本属性时，则只显示输入框
newstart-fujian 如果有附件功能，会在此处获得到数组，双向绑定
newstart-submit绑定发送后触发的事件
注意事项，
(1)由于本指令样式原因，采用相对位置定位，显示在父级别容器的最底部。注意父容器需要设置position:relative;
(2)需要依赖ngAnimate动画库，以及angularFileUpload上传组件
实例：
<div class="test">
<textarea newstart-textarea="mytext"  newstart-submit="mysubmit()" newstart-btn="face,fujian" newstart-fujian="myfujian" ng-model="mytext" ></textarea>
</div>
**/
var app = angular.module("nstdirective", ['ngAnimate', 'angularFileUpload']);
app.directive("newstartTextarea", function () {
    return {
        scope: {
            textmodel: "=newstartTextarea",
            nsubmit: "&newstartSubmit",
            fileitems: "=newstartFujian"
        },
        replace: true,
        templateUrl: "/system/directive/personnel/newstart-textarea.html",
        link: function ($scope, elm, attr, controller) {

            //根据参数加载组件
            if (attr.newstartBtn != undefined) {//未声明组件，则忽略
                var btns = attr.newstartBtn.split(",")
                for (var i = 0; i < btns.length; i++) {
                    var name = btns[i];
                    if (name == "face") {
                        $scope.facebtnshow = true;
                    }
                    else if (name == "fujian") {
                        $scope.fujianbtnshow = true;
                    } else {
                        console.log("发现未知指令：" + name);
                    }

                };


            }

            //载入表情包，75个
            $scope.faceitems = [];
            for (var i = 1; i <= 75; i++) {
                $scope.faceitems.push({ index: i });
            }


            //点击输入框，展开输入模式
            elm.bind("click", function () {
                //  console.log(elm[0].innerHTML+"出"+attr.labelshowDirective);
                $scope.$apply(function () {
                    $scope.myVar = false;
                })
            });

            //输入框自增高的程序
            var txtobj = elm.find("textarea");
            txtobj.bind("keydown", function (event) {
                $scope.$apply(function () {
                    txtobj[0].style.height = txtobj[0].scrollTop + txtobj[0].scrollHeight + "px";
                })
                //console.log(txtobj[0].scrollHeight);
            });

        },
        controller: function ($scope, $document, FileUploader) {
            $scope.myVar = true; //输入框样式
            $scope.texthight = 1; //输入框高度
            $scope.faceshow = false; //是否显示表情
            $scope.fileitems = []; //上传文件列表
            //文件上传
            var uploader = $scope.uploader = new FileUploader({
                url: 'http://ke.edu-paas.com/up/Wkup'//文件上传地址，文件上传到对应企业的附件文件夹
            });
            uploader.filters.push({
                name: 'customFilter',
                fn: function (item /*{File|FileLikeObject}*/, options) {
                    return this.queue.length < 10;
                }
            });
            uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {// 选择文件后失败 
                console.info('onWhenAddingFileFailed', item, filter, options);
            };
            uploader.onAfterAddingFile = function (fileItem) {//已经选择了文件
                var hzm = fileItem.file.name;
                if ($scope.fileflag(hzm)) { // 文件
                    fileItem.upload();
                }
                else {                                    // 文件格式不正确
                    $scope.adderr(hzm + "文件格式不正确");
                    //console.info('onAfterAddingFile文件上传格式错误');
                }
            };

            // 过滤文件 bool
            $scope.fileflag = function (hzm) {
                return (hzm.indexOf(".ppt") >= 0 || hzm.indexOf(".pptx") >= 0 ||
    				hzm.indexOf(".pdf") >= 0 || hzm.indexOf(".xls") >= 0 ||
    				hzm.indexOf(".xlsx") >= 0 || hzm.indexOf(".doc") >= 0 ||
    				hzm.indexOf(".docx") >= 0 || hzm.indexOf(".jpg") >= 0 || hzm.indexOf(".png") >= 0
    				|| hzm.indexOf(".jpge") >= 0 || hzm.indexOf(".gif") >= 0);
            };

            uploader.onAfterAddingAll = function (addedFileItems) {// 选择文件后添加到队列   1 
                console.info('onAfterAddingAll', addedFileItems);
            };
            uploader.onBeforeUploadItem = function (item) {// 2 上传之前一项
                console.info('onBeforeUploadItem', item);
            };
            uploader.onProgressItem = function (fileItem, progress) {// 3 上传进度
                console.info('onProgressItem', fileItem, progress);
            };
            uploader.onProgressAll = function (progress) {//4 队列进度
                //console.info('onProgressAll', progress);
            };
            uploader.onSuccessItem = function (fileItem, response, status, headers) {// 5上传成功
                //console.info('onSuccessItem', fileItem, response, status, headers);//fileItem 请求信息 response: 返回值status: 返回状态  headers: 请求头
                fileItem.file.url = response;
                $scope.fileitems.push(fileItem.file);
            };
            uploader.onErrorItem = function (fileItem, response, status, headers) {// 5上传失败
                $scope.adderr(fileItem.file.name + "上传错误");
                fileItem.remove();
            };
            uploader.onCancelItem = function (fileItem, response, status, headers) {//5取消上传
                console.info('onCancelItem', fileItem, response, status, headers);
            };
            uploader.onCompleteItem = function (fileItem, response, status, headers) {//6     单文件上传完成
                console.info('onCompleteItem', fileItem, response, status, headers);
            };
            uploader.onCompleteAll = function () {// 6 单文件上传完成或者队列上传完成的时候
                console.info('onCompleteAll');
            };


            //点击非指定区域，关闭显示层
            $document.bind("click", function (evt) {
                var evt = window.event ? window.event : evt,
                target = evt.srcElement || evt.target;
                if ($document[0].getElementById("jisushurukuangform") != null) {
                    var bt = $document[0].getElementById("jisushurukuangform").contains(target);
                    if (!bt) {

                        $scope.$apply(function () {
                            $scope.myVar = true;
                            $scope.faceshow = false;
                        })
                    }
                }
            });
            //控制表情窗口显示位置
            $scope.faceboxshowbtn = function (obj) {
                $scope.faceboxcss = 'qqFacewz' + obj;
                $scope.faceshow = true;
            }
            //对输入内容快捷键
            $scope.myKeyup = function (e) {
                var keycode = window.event ? e.keyCode : e.which;
                //快捷键
                if (keycode == 13 && e.shiftKey) {
                    //shift+enter
                    $scope.texthight++;
                    //console.log('想换行回车了');
                }
                else if (keycode == 13) {
                    // console.log('回车了');
                    $scope.nsubmit();
                    return;
                }

            };

            //增加表情方法
            $scope.addface = function (name) {
                //console.log(name);
                $scope.faceshow = false;
                $scope.textmodel = $scope.textmodel + "[face_" + name + "]";
                $document[0].getElementById("jisushurukuangform").focus();
            }

            //错误日志处理
            $scope.adderr = function (msg) {
                alert(msg);
            }

        }
    };
});
//本指令用于将img图标，根据文件名显示成对应后缀名的图标
app.directive("newstartSrc", function () {
    return {
        link: function (scope, element, attrs) {

            var namec = attrs.newstartSrc; //.tolocaleLowerCase();
            var houzhui = namec.substring(namec.lastIndexOf(".") + 1, namec.length);
            console.log(houzhui);
            attrs.$set("src", "/images/fileicon/" + houzhui + "_56.png");
        }
    }
});
app.directive("errSrc", function () {
    return {
        link: function (scope, element, attrs) {
            element.bind("error", function () {
                if (attrs.src != attrs.errSrc) {
                    attrs.$set("src", attrs.errSrc);
                }
            });
        }
    }
});

app.directive("divedit", function () {
    return {
        scope: {},
        restrict: 'AE',
        link: function ($scope, element, attr) {
            //输入框自增高的程序
            var txtobj = element.find("textarea");
            txtobj.bind("keydown", function (event) {
                $scope.$apply(function () {
                    txtobj[0].style.height = txtobj[0].scrollTop + txtobj[0].scrollHeight + "px";
                })
                //console.log(txtobj[0].scrollHeight);
            });
        }
    }
});

/*
app.directive("aaaa", function () {
return {
scope: { },
replace: true,
restrict: 'AE',
link: function ($scope, elm, attr, controller) {

//点击输入框，展开输入模式
elm.bind("click", function () {
//  console.log(elm[0].innerHTML+"出"+attr.labelshowDirective);
$scope.$apply(function () {
$scope.stateflag = false;
})
});
},
controller: function ($scope, $document, FileUploader) {
$scope.stateflag = true; //输入框样式        
//点击非指定区域，关闭显示层
$document.bind("click", function (evt) {
var evt = window.event ? window.event : evt,
target = evt.srcElement || evt.target;
var bt = $document[0].getElementById("newlyaddejgrjszhzt").contains(target);
if (!bt) {

$scope.$apply(function () {
$scope.stateflag = true;
})
}
});

}
};
});
*/